#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/6/12 0012 19:31
# @Author  : wzy
# @Site    : 
# @File    : runAll.py
# @Software: PyCharm


import os
import common.HTMLTestRunner as HTMLTestRunner
from testFile.getpathInfo import get_path
from testFile.readconfig import readConfig
import unittest
from  common.configEmail import send
base_path = get_path()
report = os.path.join(base_path,'result')
caseLlist = base_path + "\\testFile"
on_off = readConfig.get_email('on_off')

class AllTest:
    def __init__(self):
        '''
        初始化
        '''
        global resultReport
        resultReport = os.path.join(report,"report.HTML")
        # 开关路劲
        self.caseListFile = os.path.join(caseLlist,"caselist.txt")
        # 断言文件test01case.py
        self.caseFile = os.path.join(base_path,"testcase")
        # 取出 断言文件test01case.py 中所有的测试用例，加入列表中
        self.caselist = []

    def set_case_list(self):
        '''
        获取所有需要执行的用例 加入caselist
        :return:
        '''
        fb = open(self.caseListFile)
        for val in fb.readlines():
            data = str(val)
            if data != '' and not data.startswith("#"):
                # 去除空格 并且 换行
                self.caselist.append(data.replace("\n", ""))
        fb.close()

    def set_case_suite(self):
        '''
        使用套件
        :return:
        '''
        self.set_case_list()
        test_suite = unittest.TestSuite()
        test_module = []
        for case in  self.caselist:
            # user / test01case  获取test01case 就是用例名字
            case_name = case.split('/')[-1]
            print("执行文件----------->"+case_name+".py")
            # 批量加载  wzy/testcase/下用例文件
            discovers = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name+".py", top_level_dir=None)
            test_module.append(discovers) #存入元素组
        if len(test_module) > 0:
            for suite in test_module:
                for test_name in suite:
                    # 将需要测试的用例加入套件元素组中
                    test_suite.addTest(test_name)
        else:
            print("---test+module 无内容")
            return None
        return test_suite


    def run(self):
        '''
        开始进行测试
        :return:
        '''
        try:
            suite = self.set_case_suite()
            print("开始-----")
            if suite is not None:
                fp1 = open(resultReport,'wb')
                # 调用httprunner
                runner = HTMLTestRunner.HTMLTestRunner(stream=fp1,title='Test report',description='descripition')
                runner.run(suite)
            else:
                print("suite 为空")
        except Exception as ex:
            print(str(ex))
        finally:
            print("结束--------")
        fp1.close()
        #判断配置文件中邮件发送开关
        if on_off =='on':
            send()
        else:
            print("打开邮件发送开关")

if __name__ == '__main__':
    allrun = AllTest()
    allrun.run()
